package com.khalil.kkadmin.common.email;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.util.Map;


public class MailSenderTool {

    private final JavaMailSenderImpl mailSender;

    public MailSenderTool(MailAccount account) {
        mailSender = new JavaMailSenderImpl();
        mailSender.setHost(account.getHost());
        mailSender.setPort(account.getPort());
        mailSender.setProtocol(account.getProtocol());
        mailSender.setUsername(account.getUsername());
        mailSender.setPassword(account.getPassword());
        Map<String, String> properties = account.getProperties();
        if (properties != null) {
            properties.forEach((k, v) -> mailSender.getJavaMailProperties().put(k, v));
        }
    }

    public void sendEmail(Mail builder) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            // true表示构建一个可以带附件的邮件对象
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

            // 设置发件人
            helper.setFrom(builder.getFrom());
            // 收件人
            helper.setTo(builder.getTo());
            // 抄送人
            if (builder.getCc() != null && builder.getCc().length > 0) {
                helper.setCc(builder.getCc());
            }
            // 密送
            if (builder.getBcc() != null && builder.getBcc().length > 0) {
                helper.setBcc(builder.getBcc());
            }

            // 邮件主题
            helper.setSubject(builder.getSubject());
            // 邮件内容，html=true，表示是html格式
            helper.setText(builder.getText(), builder.getIsHtml());

            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
